package LC;

/**
 * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/
 * Say you have an array for which the ith element is the price of a given stock on day i.
 * Design an algorithm to find the maximum profit. You may complete at most two transactions.
 * Note:
 * You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
 */
public class LC_124_BinaryTreeMaximumPathSum_BinaryTree_Recur {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.right = new TreeNode(3);
        root.right.left = new TreeNode(2);
        int sum = Solution.maxPathSum(root);
        System.out.println(sum);
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    static class Solution {
        static int maxSum = Integer.MIN_VALUE;

        static int maxPathSum(TreeNode root) {
            if (root == null) return 0;
            getMaxSumWithCurNode(root);
            return maxSum;
        }

        static int getMaxSumWithCurNode(TreeNode curNode) {
            int lmax = 0, rmax = 0;
            int value = curNode.val;
            if (curNode.left != null) lmax = getMaxSumWithCurNode(curNode.left);
            if (curNode.right != null) rmax = getMaxSumWithCurNode(curNode.right);
            value = value + (lmax > 0 ? lmax : 0) + (rmax > 0 ? rmax : 0);
            if (value > maxSum) maxSum = value;
            return curNode.val + Math.max(lmax > 0 ? lmax : 0, rmax > 0 ? rmax : 0);
        }
    }
}
